package com.alibaba.citrus.cr.sales.plan.facade.service.setting.contract;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.lock.RedisLock;
import com.alibaba.citrus.cr.common.log.CommonErrorCode;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.setting.contract.ContractWriteService;
import com.alibaba.citrus.cr.sales.plan.api.setting.contract.trategy.ContractStatStrategy;
import com.alibaba.citrus.cr.sales.plan.contants.SalesPlanLockKey;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryContractRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanScItemExtendRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAdjustDetailBatchQueryRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.setting.contract.strategy.ContractStatStrategyContext;
import com.alibaba.citrus.cr.sales.plan.functions.contract.ContractAbility;
import com.alibaba.citrus.cr.sales.plan.functions.contract.ContractEntity;
import com.alibaba.citrus.cr.sales.plan.functions.contract.ContractFactory;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.repository.ContractRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAdjustDetailRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanScItemExtendRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.ContractSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanAdjustDetailSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanPublishSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemExtendSDO;
import com.alibaba.citrus.cr.sales.plan.api.statistics.SalesPlanStatService;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.mq.runtime.EpochMessageService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.CategorySDO;
import com.epoch.app.bcorder.model.dto.QueryCategoryInfoByIdsRequest;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.sales_plan.SendMessageChangeCategoryInfo;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.QueryPlanDetailByAddressIdRequest;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.QueryPlanDetailByAddressIdResponse;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.model.BoSalesPlanDetailIndex;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.service.BoSalesPlanDetailIndexService;
import com.epoch.app.bcorder.sales_plan.contract.dto.ContractLoadListRequest;
import com.epoch.app.bcorder.sales_plan.contract.dto.LoadContractByAddressIdRequest;
import com.epoch.app.bcorder.sales_plan.contract.dto.LoadContractByAddressIdResponse;
import com.epoch.app.bcorder.sales_plan.contract.dto.QueryCountByYearRequest;
import com.epoch.app.bcorder.sales_plan.contract.model.Contract;
import com.epoch.app.bcorder.sales_plan.contract.service.ContractService;
import com.epoch.app.bcorder.sales_plan.planscitemextend.service.PlanScItemExtendService;
import com.epoch.app.bcorder.sales_plan.salesplanadjustdetail.dto.UpdateByAddressIdRequest;
import com.epoch.app.bcorder.sales_plan.salesplanadjustdetail.dto.UpdateScItemCategoryRequest;
import com.epoch.app.bcorder.sales_plan.salesplanadjustdetail.service.SalesPlanAdjustDetailService;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.UpdateSalesPlanDetailResponse;
import com.epoch.app.bcorder.sales_plan.salesplandetail.model.SalesPlanDetail;
import com.epoch.app.bcorder.sales_plan.salesplandetail.service.SalesPlanDetailService;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryByIdsRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class ContractWriteServiceImpl implements ContractWriteService {

    Log log = Log.getLogger(ContractWriteServiceImpl.class);

    @Resource
    private ContractStatStrategyContext contractStatStrategyContext;

    @Resource
    private ContractAbility contractAbility;

    @Resource
    private ContractRepository contractRepository;

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private ContractService contractService;

    @Resource
    private SalesPlanDetailService salesPlanDetailService;

    @Resource
    private SalesPlanStatService salesPlanStatService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private EpochMessageService messageService;

    @Resource
    private SalesPlanScItemExtendRepository salesPlanScItemExtendRepository;

    @Resource
    private SalesPlanAdjustDetailRepository salesPlanAdjustDetailRepository;

    @Resource
    private BoSalesPlanDetailIndexService boSalesPlanDetailIndexService;

    @Resource
    private SalesPlanAdjustDetailService salesPlanAdjustDetailService;

    @Resource(name = "contractStatTaskExecutor")
    private ThreadPoolTaskExecutor contractStatTaskExecutor;

    @FacadeInvoker
    @Override
    public Result<Integer> batchCreateContract(List<ContractSDO> createContractRequestList) {
        Integer count = contractAbility.batchCreateContract(createContractRequestList);
        return Result.success(count);
    }

    @FacadeInvoker
    @Override
    public Result<Integer> editContract(ContractSDO editContractRequest) {
        ContractEntity entity = ContractFactory.load(editContractRequest);
        ContractSDO editContractSDO = editContractConverter(entity.getContractSDO(), editContractRequest);
        entity.setContractSDO(editContractSDO);
        Integer result = entity.doEdit();
        return Result.success(result);
    }

    private ContractSDO editContractConverter(ContractSDO contractSDO, ContractSDO editContractRequest) {

        if (editContractRequest.getJanQuantity() != null) {
            contractSDO.setJanQuantity(editContractRequest.getJanQuantity());
        }
        if (editContractRequest.getFebQuantity() != null) {
            contractSDO.setFebQuantity(editContractRequest.getFebQuantity());
        }
        if (editContractRequest.getMarQuantity() != null) {
            contractSDO.setMarQuantity(editContractRequest.getMarQuantity());
        }
        if (editContractRequest.getAprQuantity() != null) {
            contractSDO.setAprQuantity(editContractRequest.getAprQuantity());
        }
        if (editContractRequest.getMayQuantity() != null) {
            contractSDO.setMayQuantity(editContractRequest.getMayQuantity());
        }
        if (editContractRequest.getJuneQuantity() != null) {
            contractSDO.setJuneQuantity(editContractRequest.getJuneQuantity());
        }
        if (editContractRequest.getJulyQuantity() != null) {
            contractSDO.setJulyQuantity(editContractRequest.getJulyQuantity());
        }
        if (editContractRequest.getAugQuantity() != null) {
            contractSDO.setAugQuantity(editContractRequest.getAugQuantity());
        }
        if (editContractRequest.getSeptQuantity() != null) {
            contractSDO.setSeptQuantity(editContractRequest.getSeptQuantity());
        }
        if (editContractRequest.getOctQuantity() != null) {
            contractSDO.setOctQuantity(editContractRequest.getOctQuantity());
        }
        if (editContractRequest.getNovQuantity() != null) {
            contractSDO.setNovQuantity(editContractRequest.getNovQuantity());
        }
        if (editContractRequest.getDecQuantity() != null) {
            contractSDO.setDecQuantity(editContractRequest.getDecQuantity());
        }
        return contractSDO;
    }


    @FacadeInvoker
    @Override
    public Result<Boolean> summaryContract() {
        List<String> contractYear = contractRepository.queryContractYear();
        if (CollectionUtils.isEmpty(contractYear)) {
            return Result.success(true);
        }
        contractRepository.deleteStatContract(contractYear, null);
        for (String year : contractYear) {
            for (ContractStatDimensionEnum dimensionEnum : ContractStatDimensionEnum.getList()) {
                if (dimensionEnum.getDimension().equals(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getDimension())) {
                    continue;
                }
                ContractStatStrategy contractStatStrategy = contractStatStrategyContext.getStrategyByDimension(dimensionEnum.getDimension());
                contractStatStrategy.summary(year);
            }
        }
        return Result.success(true);
    }

    @FacadeInvoker
    @Override
    public Result<Boolean> summaryContractByYear(String year, String orgBusinessUnitCode) {
        log.info("ContractWriteServiceImpl_summaryContractByYear_req_year={},orgBusinessUnitCode={}", year, orgBusinessUnitCode);
        summaryContractByYearCheck(year, orgBusinessUnitCode);
        String statLockKey = StringUtil.isNotEmpty(orgBusinessUnitCode) ? year + orgBusinessUnitCode : year + "0000000000";
        try (RedisLock lock = new RedisLock(BcOrderConstants.REDIS_CACHE_CODE(), SalesPlanLockKey.getContractStatLockKey(statLockKey))) {
            boolean locked = lock.lock();
            if (!locked) {
                return Result.fail("OTS-02-001-00-16-022", "合同量正在汇总，请稍后重试");
            }
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            //contractRepository.deleteStatContract(Lists.newArrayList(year),orgBusinessUnitCode);
            //通过线程并发拉取"客户送达方 - 货品维度"的所有明细数据
            List<ContractSDO> allContractList = getContractSDOList(year, orgBusinessUnitCode);
            log.info("ContractWriteServiceImpl_summaryContractByYear_allContractList_size={}", allContractList.size());

            //通过线程并发执行16个维度汇总
            List<Future<String>> futureList = Lists.newArrayList();
            for (ContractStatDimensionEnum dimensionEnum : ContractStatDimensionEnum.getList()) {
                if (dimensionEnum.getDimension().equals(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getDimension())) {
                    continue;
                }
                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                    try {
                        ContractStatStrategy contractStatStrategy = contractStatStrategyContext.getStrategyByDimension(dimensionEnum.getDimension());
                        return contractStatStrategy.summaryV2(allContractList, year, orgBusinessUnitCode);
                    } catch (Exception e) {
                        log.error("ContractWriteServiceImpl_summaryContractByYear_fail,ContractWriteServiceImpl_summaryContractByYear_contractStatStrategy_error={}", e);
                    }
                    return "error";
                }, contractStatTaskExecutor);
                futureList.add(future);
            }

            List<String> result = new ArrayList<>();
            try {
                for (Future<String> future : futureList) {
                    String b = future.get();
                    result.add(b);
                }
                log.info("ContractWriteServiceImpl_summaryContractByYear_result={}", JSONObject.toJSON(result));
            } catch (Exception e) {
                log.error("ContractWriteServiceImpl_summaryContractByYear_fail,ContractWriteServiceImpl_summaryContractByYear_error={}", e);
            }
            stopWatch.stop();
            log.info("ContractWriteServiceImpl_summaryContractByYear_end_elapsed_time:" + stopWatch.getTotalTimeMillis() + "ms");
        } catch (FacadeException fe) {
            log.error("ContractWriteServiceImpl_summaryContractByYear_fail={}", fe.getMessage());
            return Result.fail(fe.getErrorCode(), fe.getErrorMessage());
        } catch (Exception e) {
            log.error("ContractWriteServiceImpl_summaryContractByYear_fail={}", e.getMessage());
            return Result.fail(CommonErrorCode.SYSTEM_ERROR, "系统开小差了");
        }
        return Result.success(true);
    }

    private void summaryContractByYearCheck(String year, String orgBusinessUnitCode) {
        if (StringUtils.isBlank(year)) {
            throw new FacadeException("OTS-02-001-00-16-024");
        }
        if (year.length() != 4 || !StringUtils.isNumeric(year)) {
            throw new FacadeException("OTS-02-001-00-16-025");
        }
        QueryCountByYearRequest byYearRequest = new QueryCountByYearRequest();
        byYearRequest.setYear(year);
        byYearRequest.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
        byYearRequest.setOrgBusinessUnitCode(orgBusinessUnitCode);
        Integer count = contractRepository.queryCountByYear(byYearRequest);
        if (count == null || count == 0) {
            throw new FacadeException("OTS-02-001-00-16-023", year);
        }
    }

    private List<ContractSDO> getContractSDOList(String year, String orgBusinessUnitCode) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        List<Future<List<ContractSDO>>> futureList = Lists.newArrayList();
        QueryCountByYearRequest byYearRequest = new QueryCountByYearRequest();
        byYearRequest.setYear(year);
        byYearRequest.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
        byYearRequest.setOrgBusinessUnitCode(orgBusinessUnitCode);
        int total = contractRepository.queryCountByYear(byYearRequest);
        log.info("ContractWriteServiceImpl_summaryContractByYear_queryCountByYear_total={}", total);
        int pageSize = 1000;
        int totalPage = total / pageSize;
        if (total % pageSize > 0) {
            totalPage++;
        }

        List<ContractSDO> result = new ArrayList<>();

        // 应急方案，防止数据库CPU抗不住了才需要打开深度查询优化开关，并且记录数大于20000，才走优化接口
        if (BcOrderConstants.DEPTH_QUERY_SWITCH().equals("true") && totalPage > 20) {
            PageQueryContractRequest pageQueryContractRequest = new PageQueryContractRequest();
            pageQueryContractRequest.setContractYear(year);
            pageQueryContractRequest.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
            pageQueryContractRequest.setOrgBusinessUnitCode(orgBusinessUnitCode);
            pageQueryContractRequest.setSize(pageSize);
            result = getContractSDOListForDepthQuery(pageQueryContractRequest, totalPage);
        } else {
            for (int pageNo = 0; pageNo < totalPage; pageNo++) {
                int start = pageNo * pageSize;
                CompletableFuture<List<ContractSDO>> future = CompletableFuture.supplyAsync(() -> {
                    PageResult<List<ContractSDO>> pageResult = null;
                    try {
                        PageQueryContractRequest pageQueryContractRequest = new PageQueryContractRequest();
                        pageQueryContractRequest.setContractYear(year);
                        pageQueryContractRequest.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
                        pageQueryContractRequest.setOrgBusinessUnitCode(orgBusinessUnitCode);
                        pageQueryContractRequest.setStart(start);
                        pageQueryContractRequest.setSize(pageSize);
                        pageResult = contractRepository.simplePageQueryContract(pageQueryContractRequest);
                        if (pageResult == null || CollectionUtils.isEmpty(pageResult.getContent())) {
                            return Lists.newArrayList();
                        }
                    } catch (Exception e) {
                        log.error("ContractWriteServiceImpl_summaryContractByYear_getContractSDOList_error,多线程拉取合同数据异常={}", e);
                        return Lists.newArrayList();
                    }
                    return pageResult.getContent();
                }, contractStatTaskExecutor);
                futureList.add(future);
            }

            try {
                for (Future<List<ContractSDO>> future : futureList) {
                    List<ContractSDO> subList = future.get();
                    result.addAll(subList);
                }
            } catch (Exception e) {
                log.error("ContractWriteServiceImpl_summaryContractByYear_getContractSDOList_error,获取多线程合同结果异常={}", e);
            }
        }

        if (total != result.size()) {
            throw new FacadeException(ErrorMessage.code("OTS-02-001-00-16-040"));
        }
        stopWatch.stop();
        log.info("ContractWriteServiceImpl_summaryContractByYear_getContractSDOList_elapsed_time={}, total={}, DEPTH_QUERY_SWITCH={}", stopWatch.getTotalTimeMillis(), total, BcOrderConstants.DEPTH_QUERY_SWITCH());
        return result;
    }

    /**
     * 优化深度分页查询
     *
     * @param pageQueryContractRequest
     * @param totalPage
     * @return
     */
    private List<ContractSDO> getContractSDOListForDepthQuery(PageQueryContractRequest pageQueryContractRequest, int totalPage) {
        List<ContractSDO> allContractSDO = new ArrayList<>();
        Long maxId = null;
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            maxId = getContractSDOListByGreaterId(pageQueryContractRequest, maxId, allContractSDO);
            if (maxId == null) {
                return allContractSDO;
            }
        }
        return allContractSDO;
    }

    private Long getContractSDOListByGreaterId(PageQueryContractRequest pageQueryContractRequest, Long maxId, List<ContractSDO> allContractSDO) {
        PageResult<List<ContractSDO>> pageResult = null;
        try {
            pageQueryContractRequest.setGreaterId(maxId);
            pageQueryContractRequest.setStart(0);
            pageResult = contractRepository.simplePageQueryContract(pageQueryContractRequest);
            if (pageResult == null || CollectionUtils.isEmpty(pageResult.getContent())) {
                return null;
            }
        } catch (Exception e) {
            log.error(StringUtils.join("ContractWriteServiceImpl_summaryContractByYear_getContractSDOListByGreaterId_error,pageQueryContractRequest=", JSON.toJSONString(pageQueryContractRequest)), e);
            return null;
        }
        List<ContractSDO> contractSDOS = pageResult.getContent();
        allContractSDO.addAll(contractSDOS);
        // 取最后一条记录ID（返回最大ID） 依赖数据库单表且是自增主键，同时查询条件是按ID正排序的
        return contractSDOS.get(contractSDOS.size() - 1).getId();
    }

    @Override
    @FacadeInvoker
    public Result<Integer> editCustomerContract(ContractSDO editContractRequest) {
        if (editContractRequest == null || editContractRequest.getId() == null) {
            return Result.fail(0, "OTS-02-001-00-15-013", ErrorMessage.code("OTS-02-001-00-15-013", null).getDisplayErrorMessage());
        }
        setYuanToFen(editContractRequest);
        //年合同量
        Integer annualQuantity = editContractRequest.getJanQuantity() + editContractRequest.getFebQuantity() + editContractRequest.getMarQuantity() +
                editContractRequest.getAprQuantity() + editContractRequest.getMayQuantity() + editContractRequest.getJuneQuantity() +
                editContractRequest.getJulyQuantity() + editContractRequest.getAugQuantity() + editContractRequest.getSeptQuantity() +
                editContractRequest.getOctQuantity() + editContractRequest.getNovQuantity() + editContractRequest.getDecQuantity();
        editContractRequest.setAnnualQuantity(annualQuantity);
        //年合同金额
        Long annualAmount = editContractRequest.getJanAmount() + editContractRequest.getFebAmount() + editContractRequest.getMarAmount() +
                editContractRequest.getAprAmount() + editContractRequest.getMayAmount() + editContractRequest.getJuneAmount() +
                editContractRequest.getJulyAmount() + editContractRequest.getAugAmount() + editContractRequest.getSeptAmount() +
                editContractRequest.getOctAmount() + editContractRequest.getNovAmount() + editContractRequest.getDecAmount();
        ContractEntity entity = ContractEntity.of(editContractRequest);
        editContractRequest.setAnnualAmount(annualAmount);
        //年折后金额
        Long annualAfterDiscount = editContractRequest.getJanAfterDiscount() + editContractRequest.getFebAfterDiscount() + editContractRequest.getMarAfterDiscount() +
                editContractRequest.getAprAfterDiscount() + editContractRequest.getMayAfterDiscount() + editContractRequest.getJuneAfterDiscount() +
                editContractRequest.getJulyAfterDiscount() + editContractRequest.getAugAfterDiscount() + editContractRequest.getSeptAfterDiscount() +
                editContractRequest.getOctAfterDiscount() + editContractRequest.getNovAfterDiscount() + editContractRequest.getDecAfterDiscount();
        editContractRequest.setAnnualAfterDiscount(annualAfterDiscount);
        //年折前带税销售额
        Long annualTaxIncludedBeforeTax = editContractRequest.getJanTaxIncludedBeforeTax() + editContractRequest.getFebTaxIncludedBeforeTax() + editContractRequest.getMarTaxIncludedBeforeTax() +
                editContractRequest.getAprTaxIncludedBeforeTax() + editContractRequest.getMayTaxIncludedBeforeTax() + editContractRequest.getJuneTaxIncludedBeforeTax() +
                editContractRequest.getJulyTaxIncludedBeforeTax() + editContractRequest.getAugTaxIncludedBeforeTax() + editContractRequest.getSeptTaxIncludedBeforeTax() +
                editContractRequest.getOctTaxIncludedBeforeTax() + editContractRequest.getNovTaxIncludedBeforeTax() + editContractRequest.getDecTaxIncludedBeforeTax();
        editContractRequest.setAnnualTaxIncludedBeforeTax(annualTaxIncludedBeforeTax);
        entity.setContractSDO(editContractRequest);
        return Result.success(entity.doEdit());
    }

    private void setYuanToFen(ContractSDO editContractRequest) {
        editContractRequest.setJanQuantity(panNull(editContractRequest.getJanQuantity()));
        editContractRequest.setFebQuantity(panNull(editContractRequest.getFebQuantity()));
        editContractRequest.setMarQuantity(panNull(editContractRequest.getMarQuantity()));
        editContractRequest.setAprQuantity(panNull(editContractRequest.getAprQuantity()));
        editContractRequest.setMayQuantity(panNull(editContractRequest.getMayQuantity()));
        editContractRequest.setJuneQuantity(panNull(editContractRequest.getJuneQuantity()));
        editContractRequest.setJulyQuantity(panNull(editContractRequest.getJulyQuantity()));
        editContractRequest.setAugQuantity(panNull(editContractRequest.getAugQuantity()));
        editContractRequest.setSeptQuantity(panNull(editContractRequest.getSeptQuantity()));
        editContractRequest.setOctQuantity(panNull(editContractRequest.getOctQuantity()));
        editContractRequest.setNovQuantity(panNull(editContractRequest.getNovQuantity()));
        editContractRequest.setOctQuantity(panNull(editContractRequest.getOctQuantity()));
        editContractRequest.setDecQuantity(panNull(editContractRequest.getDecQuantity()));

        editContractRequest.setJanAmount(yuanToFen(editContractRequest.getJanAmountString()));
        editContractRequest.setFebAmount(yuanToFen(editContractRequest.getFebAmountString()));
        editContractRequest.setMarAmount(yuanToFen(editContractRequest.getMarAmountString()));
        editContractRequest.setAprAmount(yuanToFen(editContractRequest.getAprAmountString()));
        editContractRequest.setMayAmount(yuanToFen(editContractRequest.getMayAmountString()));
        editContractRequest.setJuneAmount(yuanToFen(editContractRequest.getJuneAmountString()));
        editContractRequest.setJulyAmount(yuanToFen(editContractRequest.getJulyAmountString()));
        editContractRequest.setAugAmount(yuanToFen(editContractRequest.getAugAmountString()));
        editContractRequest.setSeptAmount(yuanToFen(editContractRequest.getSeptAmountString()));
        editContractRequest.setOctAmount(yuanToFen(editContractRequest.getOctAmountString()));
        editContractRequest.setNovAmount(yuanToFen(editContractRequest.getNovAmountString()));
        editContractRequest.setOctAmount(yuanToFen(editContractRequest.getOctAmountString()));
        editContractRequest.setDecAmount(yuanToFen(editContractRequest.getDecAmountString()));

        editContractRequest.setJanAfterDiscount(yuanToFen(editContractRequest.getJanAmountString()));
        editContractRequest.setFebAfterDiscount(yuanToFen(editContractRequest.getFebAmountString()));
        editContractRequest.setMarAfterDiscount(yuanToFen(editContractRequest.getMarAmountString()));
        editContractRequest.setAprAfterDiscount(yuanToFen(editContractRequest.getAprAmountString()));
        editContractRequest.setMayAfterDiscount(yuanToFen(editContractRequest.getMayAmountString()));
        editContractRequest.setJuneAfterDiscount(yuanToFen(editContractRequest.getJuneAmountString()));
        editContractRequest.setJulyAfterDiscount(yuanToFen(editContractRequest.getJulyAmountString()));
        editContractRequest.setAugAfterDiscount(yuanToFen(editContractRequest.getAugAmountString()));
        editContractRequest.setSeptAfterDiscount(yuanToFen(editContractRequest.getSeptAmountString()));
        editContractRequest.setOctAfterDiscount(yuanToFen(editContractRequest.getOctAmountString()));
        editContractRequest.setNovAfterDiscount(yuanToFen(editContractRequest.getNovAmountString()));
        editContractRequest.setDecAfterDiscount(yuanToFen(editContractRequest.getDecAmountString()));

        editContractRequest.setJanTaxIncludedBeforeTax(yuanToFen(editContractRequest.getJanTaxIncludedBeforeTaxString()));
        editContractRequest.setFebTaxIncludedBeforeTax(yuanToFen(editContractRequest.getFebTaxIncludedBeforeTaxString()));
        editContractRequest.setMarTaxIncludedBeforeTax(yuanToFen(editContractRequest.getMarTaxIncludedBeforeTaxString()));
        editContractRequest.setAprTaxIncludedBeforeTax(yuanToFen(editContractRequest.getAprTaxIncludedBeforeTaxString()));
        editContractRequest.setMayTaxIncludedBeforeTax(yuanToFen(editContractRequest.getMayTaxIncludedBeforeTaxString()));
        editContractRequest.setJuneTaxIncludedBeforeTax(yuanToFen(editContractRequest.getJuneTaxIncludedBeforeTaxString()));
        editContractRequest.setJulyTaxIncludedBeforeTax(yuanToFen(editContractRequest.getJulyTaxIncludedBeforeTaxString()));
        editContractRequest.setAugTaxIncludedBeforeTax(yuanToFen(editContractRequest.getAugTaxIncludedBeforeTaxString()));
        editContractRequest.setSeptTaxIncludedBeforeTax(yuanToFen(editContractRequest.getSeptTaxIncludedBeforeTaxString()));
        editContractRequest.setOctTaxIncludedBeforeTax(yuanToFen(editContractRequest.getOctTaxIncludedBeforeTaxString()));
        editContractRequest.setNovTaxIncludedBeforeTax(yuanToFen(editContractRequest.getNovTaxIncludedBeforeTaxString()));
        editContractRequest.setDecTaxIncludedBeforeTax(yuanToFen(editContractRequest.getDecTaxIncludedBeforeTaxString()));

    }

    private long yuanToFen(String price) {
        if (StringUtils.isBlank(price)) {
            return 0;
        }
        BigDecimal multiply = new BigDecimal(price).multiply(new BigDecimal("100"));
        return multiply.longValue();
    }

    private Integer panNull(Integer quantity) {
        if (quantity == null) {
            return 0;
        }
        return quantity;
    }

    /**
     * 一、生产
     * 1、记录分派idList
     * 2、sendMessage
     * 二、消费
     * 3、根据id查询客户地址，拿到地址编码
     * 4、查询合同量，（update）（业务单元、组织、渠道、部门、负责人）
     * 5、触发合同量汇总接口
     * 6、根据地址编码+明细状态非已完成，当作入参查月度计划明细
     * 7、更新月度计划明细、更新调整中的明细
     * 8、触发汇总
     *
     * @param message
     * @return
     */
    @Override
    public Result<Boolean> consumeCustomerAddressToCollect(String message) {
        //20220909, 从产品需求上可暂时去掉触发合同量修改汇总
        if(true){
            return Result.success(true);
        }
        // 参数校验
        if (StringUtils.isBlank(message)) {
            return Result.success(true);
        }
        List<String> idList = JSONObject.parseArray(message, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            return Result.success(true);
        }
        // 查询变更的客户地址
        BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
        batchQueryByIdsRequest.setIdList(idList);
        Result<List<CustomerAddress>> listResult = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
            log.error("ContractWriteServiceImpl.consumeCustomerAddressToCollect CustomerAddress not found request:" + message);
            return Result.success(true);
        }
        List<CustomerAddress> customerAddressList = listResult.getResult();
        Set<String> planIdAllSet = Sets.newHashSet();
        Set<String> orgBusinessUnitCodeSet = Sets.newHashSet();
        // 客户地址五键唯一(销售组织、客户编码、地址编码、业务渠道、货品组)
        for (CustomerAddress customerAddress : customerAddressList) {
            try {
                // 修改合同量中的销售渠道、销售部门、负责人（业务员）
                Set<String> orgBusinessUnitCodes = updateContract(customerAddress);
                if (CollectionUtils.isNotEmpty(orgBusinessUnitCodeSet)) {
                    orgBusinessUnitCodeSet.addAll(orgBusinessUnitCodes);
                }
                // 修改月度计划明细中的销售渠道、销售部门、负责人（业务员）
                Set<String> planIdSet = updateSalesPlanDetail(customerAddress);
                if (CollectionUtils.isNotEmpty(planIdSet)) {
                    planIdAllSet.addAll(planIdSet);
                }
            } catch (Exception e) {
                log.error("消息消费修改合同量、月度计划明细的客户地址信息异常", e);
                log.error("消息消费修改合同量、月度计划明细的客户地址信息异常的参数{} ", JSONObject.toJSONString(customerAddress));
            }
        }
        // 更新完成后触发一下汇总
        // 汇总合同量
        try {
            if (CollectionUtils.isNotEmpty(orgBusinessUnitCodeSet)) {
                for (String orgBusinessUnitCode : orgBusinessUnitCodeSet) {
                    summaryContractByYear(DateUtils.getYear(), orgBusinessUnitCode);
                }
            }
            // 汇总月度计划明细
            if (CollectionUtils.isNotEmpty(planIdAllSet)) {
                for (String planId : planIdAllSet) {
                    salesPlanStatService.planCollect(planId);
                }
            }
        } catch (Exception e) {
            log.error("触发合同量汇总、月度计划明细汇总异常", e);
        }
        return Result.success(true);
    }

    /**
     * 修改合同量的销售渠道、销售部门、负责人（业务员）
     *
     * @param customerAddress
     * @return
     */
    private Set<String> updateContract(CustomerAddress customerAddress) {
        // 三键唯一
//        String orgSaleOrganizationCode = customerAddress.getOrgSaleOrganizationCode();
//        String customerCode = customerAddress.getCustomerCode();
//        String addressCode = customerAddress.getAddressCode();

        // 修改的内容
        String orgSaleChannelCode = customerAddress.getOrgSaleChannelCode();
        String orgSaleDepartmentCode = customerAddress.getOrgSaleDepartmentCode();
        String principal = customerAddress.getPrincipal();

//        // 查询合同量（三键唯一）
//        ContractLoadListRequest contractLoadListRequest = new ContractLoadListRequest();
//        contractLoadListRequest.setOrgSalesOrganizationCode(orgSaleOrganizationCode);
//        contractLoadListRequest.setCustomerCode(customerCode);
//        contractLoadListRequest.setCustomerAddress(addressCode);
//        Result<List<Contract>> contractResult = contractService.loadContractList(contractLoadListRequest);
        LoadContractByAddressIdRequest contractByAddressIdRequest = new LoadContractByAddressIdRequest();
        contractByAddressIdRequest.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
        contractByAddressIdRequest.setCustomerAddressId(Objects.toString(customerAddress.getId(), null));
        LoadContractByAddressIdResponse contractResult = contractService.loadContractByAddressId(contractByAddressIdRequest);
        if (Objects.isNull(contractResult) || CollectionUtils.isEmpty(contractResult.getResult())) {
            log.error("ContractWriteServiceImpl.updateContract contractResult not find");
            return null;
        }
        List<Contract> contractList = contractResult.getResult();
        Set<String> orgBusinessUnitCodeSet = Sets.newHashSet();
        // 修改根据这三个键查询出来的合同量的值
        for (Contract contract : contractList) {
            Contract editContractRecord = new Contract();
            BeanUtils.copyProperties(contract, editContractRecord);
            editContractRecord.setOrgSalesChannelCode(orgSaleChannelCode);
            editContractRecord.setOrgSalesDepartmentCode(orgSaleDepartmentCode);
            editContractRecord.setManageEmployeeId(principal);
            contractService.updateContract(editContractRecord);
            orgBusinessUnitCodeSet.add(contract.getOrgBusinessUnitCode());
        }
        return orgBusinessUnitCodeSet;
    }

    /**
     * 修改月度计划明细的销售渠道、销售部门、负责人（业务员）
     *
     * @return
     */
    private Set<String> updateSalesPlanDetail(CustomerAddress customerAddress) {
//        // 三键唯一
//        String orgSaleOrganizationCode = customerAddress.getOrgSaleOrganizationCode();
//        String customerCode = customerAddress.getCustomerCode();
//        String addressCode = customerAddress.getAddressCode();

        // 修改的内容
        String orgSaleChannelCode = customerAddress.getOrgSaleChannelCode();
        String orgSaleDepartmentCode = customerAddress.getOrgSaleDepartmentCode();
        String principal = customerAddress.getPrincipal();
//        BatchQueryDetailRequest batchQueryDetailRequest = new BatchQueryDetailRequest();
//        batchQueryDetailRequest.setOrgSalesOrganizationCode(orgSaleOrganizationCode);
//        batchQueryDetailRequest.setCustomerCode(customerCode);
//        batchQueryDetailRequest.setAddressCode(addressCode);
//        Result<List<SalesPlanDetail>> salesPlanDetailResult = salesPlanDetailService.batchQueryDetail(batchQueryDetailRequest);

        QueryPlanDetailByAddressIdRequest addressIdRequest = new QueryPlanDetailByAddressIdRequest();
        addressIdRequest.setCustomerAddressId(Objects.toString(customerAddress.getId(), null));
        QueryPlanDetailByAddressIdResponse salesPlanDetailResult = boSalesPlanDetailIndexService.queryPlanDetailByAddressId(addressIdRequest);
        if (Objects.isNull(salesPlanDetailResult) || CollectionUtils.isEmpty(salesPlanDetailResult.getResult())) {
            return Sets.newHashSet();
        }
        List<BoSalesPlanDetailIndex> salesPlanDetailList = salesPlanDetailResult.getResult();
        Set<String> planIdList = Sets.newHashSet();
        for (BoSalesPlanDetailIndex salesPlanDetail : salesPlanDetailList) {
//            String planId = salesPlanDetail.getPlanId();
//            // 筛选掉已完成的
//            LoadSalesPlanRequest loadSalesPlanRequest = new LoadSalesPlanRequest();
//            loadSalesPlanRequest.setId(planId);
//            SalesPlan salesPlan = null;
//            try {
//                salesPlan = salesPlanService.loadSalesPlan(loadSalesPlanRequest);
//            } catch (Exception e) {
//                log.error("月度计划查询异常", e);
//                continue;
//            }
//            if (Objects.isNull(salesPlan)) {
//                continue;
//            }
//            Integer status = salesPlan.getStatus();
//            if(SalesPlanStatusEnum.PUBLISHED.getCode().equals(status)) {
//                continue;
//            }
            SalesPlanDetail editSalesPlanDetailRecord = new SalesPlanDetail();
            BeanUtils.copyProperties(salesPlanDetail, editSalesPlanDetailRecord);
            editSalesPlanDetailRecord.setPlanId(Long.valueOf(salesPlanDetail.getPlanId()));
            editSalesPlanDetailRecord.setOrgSalesChannelCode(orgSaleChannelCode);
            editSalesPlanDetailRecord.setOrgSalesDepartmentCode(orgSaleDepartmentCode);
            editSalesPlanDetailRecord.setManageEmployeeId(principal);
            UpdateSalesPlanDetailResponse response = salesPlanDetailService.updateSalesPlanDetail(editSalesPlanDetailRecord);
            if (null == response || response.getCount() < 1) {
                log.error("更新计划明细:{}失败", salesPlanDetail.getId());
            }
            planIdList.add(String.valueOf(salesPlanDetail.getPlanId()));
            //调整中的还需要更新调整忙明细
            if (null != salesPlanDetail.getOspStatus() && salesPlanDetail.getOspStatus() > SalesPlanStatusEnum.PUBLISHED.getCode()) {
//                PageQuerySalePlanRequest pageQuerySalePlanRequest = new PageQuerySalePlanRequest();
//                pageQuerySalePlanRequest.setParentId(salesPlanDetail.getPlanId());
//                pageQuerySalePlanRequest.setModel(SalesPlanModelEnum.ADJUST_MODEL.getModel());
//                pageQuerySalePlanRequest.setStatusList(Lists.newArrayList(SalesPlanStatusEnum.ADJUST.getCode(),SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getCode(),SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getCode()));
//                PageResult<List<SalesPlanSDO>> listPageResult1 = salesPlanRepository.pageQuery(pageQuerySalePlanRequest);
//
                UpdateByAddressIdRequest updateByAddressIdRequest = new UpdateByAddressIdRequest();
                updateByAddressIdRequest.setPlanDetailId(Objects.toString(salesPlanDetail.getId()));
                updateByAddressIdRequest.setOrgSalesChannelCode(orgSaleChannelCode);
                updateByAddressIdRequest.setOrgSalesDepartmentCode(orgSaleDepartmentCode);
                updateByAddressIdRequest.setManageEmployeeId(principal);
                salesPlanAdjustDetailService.updateByAddressId(updateByAddressIdRequest);
            }
        }
        return planIdList;
    }

    // 导入的类目走的也是这单个关联货品类目的接口，这个目前就设计为单个的

    /**
     * 校验货品
     * 校验类目
     * 修改合同量的货品类目
     * 修改阅读计划明细的货品类目
     * 触发合同量汇总
     * 触发月度计划明细汇总
     *
     * @param message
     * @return
     */
    @Override
    public Result<Boolean> consumeScItemCategoryToCollect(String message) {
        //20220909, 从产品需求上可暂时去掉触发合同量修改汇总
        if(true){
            return Result.success(true);
        }
        // 参数校验
        if (StringUtils.isBlank(message)) {
            return Result.success(true);
        }
        SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo = JSONObject.parseObject(message, SendMessageChangeCategoryInfo.class);
        if (Objects.isNull(sendMessageChangeCategoryInfo)) {
            return Result.success(true);
        }

        String scItemId = sendMessageChangeCategoryInfo.getScItemId();
        String categoryId = sendMessageChangeCategoryInfo.getCategoryId();
        // 校验货品
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        Map searchReqDTO = new HashMap();
        List<String> scItemIds = Lists.newArrayList(scItemId);
        searchReqDTO.put("scItemIds", scItemIds);
        searchScItemRequest.setSearchReqDTO(searchReqDTO);
        Result<List<ScItemSDO>> searchScItemResult = baseDataService.searchScItem(searchScItemRequest);
        if (null == searchScItemResult || CollectionUtils.isEmpty(searchScItemResult.getResult())) {
            log.error("consumeScItemCategoryToCollect.searchScItemResult not found");
            return Result.success(true);
        }
        // 校验类目
        QueryCategoryInfoByIdsRequest queryCategoryInfoByIdsRequest = new QueryCategoryInfoByIdsRequest();
        queryCategoryInfoByIdsRequest.setCategoryIdList(Lists.newArrayList(categoryId));
        Result<List<CategorySDO>> listResult = baseDataService.queryCategoryInfoByIds(queryCategoryInfoByIdsRequest);
        if (null == listResult || CollectionUtils.isEmpty(listResult.getResult())) {
            log.error("consumeScItemCategoryToCollect.searchCategoryResult not found");
            return Result.success(true);
        }
        Set<String> planIdAllSet = null;
        Set<String> orgBusinessUnitCodeSet = null;
        try {
            // 修改合同量的货品类目
            orgBusinessUnitCodeSet = updateContractScItemCategory(sendMessageChangeCategoryInfo);
            // 修改月度划明细的货品类目
            planIdAllSet = updateSalesPlanDetailForScItemCategory(sendMessageChangeCategoryInfo);
//            // 修改月度计划extend的货品类目
//            updateSalesPlanExtend(sendMessageChangeCategoryInfo);
//            // 修改调整明细
//            updateSalesPlanAdjust(sendMessageChangeCategoryInfo);
        } catch (Exception e) {
            log.error("消息消费修改合同量、月度计划明细的货品类目信息异常", e);
            log.error("消息消费修改合同量、月度计划明细的货品类目信息异常的参数{} ", JSONObject.toJSONString(sendMessageChangeCategoryInfo));
        }

        // 更新完成后触发一下汇总
        try {
            // 汇总合同量
            if (CollectionUtils.isNotEmpty(orgBusinessUnitCodeSet)) {
                for (String orgBusinessUnitCode : orgBusinessUnitCodeSet) {
                    summaryContractByYear(DateUtils.getYear(), orgBusinessUnitCode);
                }
            }
            // 汇总月度计划明细
            if (CollectionUtils.isNotEmpty(planIdAllSet)) {
                for (String planId : planIdAllSet) {
                    salesPlanStatService.planCollect(planId);
                }
            }
        } catch (Exception e) {
            log.error("货品类目变更触发合同汇总、月度计划明细汇总消息消费异常", e);
        }
        return Result.success(true);
    }

    /**
     * 修改月度计划调整明细表的货品类目
     *
     * @param sendMessageChangeCategoryInfo
     * @return
     */
    private Boolean updateSalesPlanAdjust(SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo) {
        // 货品
        String scItemId = sendMessageChangeCategoryInfo.getScItemId();
        // 修改的内容
        String categoryId = sendMessageChangeCategoryInfo.getCategoryId();

        SalesPlanAdjustDetailBatchQueryRequest salesPlanAdjustDetailBatchQueryRequest = new SalesPlanAdjustDetailBatchQueryRequest();
        salesPlanAdjustDetailBatchQueryRequest.setScItemId(scItemId);
        List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOS = salesPlanAdjustDetailRepository.batchQueryDetail(salesPlanAdjustDetailBatchQueryRequest);
        if (CollectionUtils.isEmpty(salesPlanAdjustDetailSDOS)) {
            return true;
        }
        for (SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO : salesPlanAdjustDetailSDOS) {
            SalesPlanAdjustDetailSDO editSalesPlanAdjustDetailSDO = SalesPlanAdjustDetailSDO.builder().build();
            BeanUtils.copyProperties(salesPlanAdjustDetailSDO, editSalesPlanAdjustDetailSDO);
            editSalesPlanAdjustDetailSDO.setScItemLeafCategoryId(categoryId);
            salesPlanAdjustDetailRepository.edit(salesPlanAdjustDetailSDO);
        }
        return true;
    }

    /**
     * 修改月度计划扩展表的货品类目（发布调整页）
     *
     * @param sendMessageChangeCategoryInfo
     * @return
     */
    private Boolean updateSalesPlanExtend(SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo) {
        // 货品
        String scItemId = sendMessageChangeCategoryInfo.getScItemId();
        // 修改的内容
        String categoryId = sendMessageChangeCategoryInfo.getCategoryId();

        QueryPlanScItemExtendRequest queryPlanScItemExtendRequest = new QueryPlanScItemExtendRequest();
        queryPlanScItemExtendRequest.setScItemId(scItemId);
        List<SalesPlanScItemExtendSDO> salesPlanScItemExtendSDOS = salesPlanScItemExtendRepository.batchQueryPlanScItemExtend(queryPlanScItemExtendRequest);
        if (CollectionUtils.isEmpty(salesPlanScItemExtendSDOS)) {
            return true;
        }
        for (SalesPlanScItemExtendSDO salesPlanScItemExtendSDO : salesPlanScItemExtendSDOS) {
            SalesPlanPublishSDO salesPlanPublishSDO = SalesPlanPublishSDO.builder().build();
            BeanUtils.copyProperties(salesPlanScItemExtendSDO, salesPlanPublishSDO);
            salesPlanPublishSDO.setScItemCategoryId(categoryId);
            salesPlanScItemExtendRepository.edit(salesPlanPublishSDO);
        }
        return true;
    }


    /**
     * 修改合同量的货品类目
     *
     * @param sendMessageChangeCategoryInfo
     * @return
     */
    private Set<String> updateContractScItemCategory(SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo) {
        // 货品
        String scItemId = sendMessageChangeCategoryInfo.getScItemId();

        // 修改的内容
        String categoryId = sendMessageChangeCategoryInfo.getCategoryId();

        // 查询合同量（根据货品id）
        ContractLoadListRequest contractLoadListRequest = new ContractLoadListRequest();
        contractLoadListRequest.setScItemId(scItemId);
        Result<List<Contract>> contractResult = contractService.loadContractList(contractLoadListRequest);
        if (Objects.isNull(contractResult) || CollectionUtils.isEmpty(contractResult.getResult())) {
            return null;
        }
        List<Contract> contractList = contractResult.getResult();
        Set<String> orgBusinessUnitCodeSet = Sets.newHashSet();
        for (Contract contract : contractList) {
            Contract editContractRecord = new Contract();
            BeanUtils.copyProperties(contract, editContractRecord);
            editContractRecord.setScItemCategoryId(categoryId);
            contractService.updateContract(editContractRecord);
            orgBusinessUnitCodeSet.add(contract.getOrgBusinessUnitCode());
        }
        return orgBusinessUnitCodeSet;
    }

    @Resource
    private PlanScItemExtendService planScItemExtendService;

    /**
     * 修改月度计划明细的货品类目
     *
     * @return
     */
    private Set<String> updateSalesPlanDetailForScItemCategory(SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo) {
        // 货品
        String scItemId = sendMessageChangeCategoryInfo.getScItemId();

        // 修改的内容
        String categoryId = sendMessageChangeCategoryInfo.getCategoryId();

//        BatchQueryDetailRequest batchQueryDetailRequest = new BatchQueryDetailRequest();
//        batchQueryDetailRequest.setScItemId(scItemId);
//        Result<List<SalesPlanDetail>> salesPlanDetailResult = salesPlanDetailService.batchQueryDetail(batchQueryDetailRequest);
        QueryPlanDetailByAddressIdRequest addressIdRequest = new QueryPlanDetailByAddressIdRequest();
        addressIdRequest.setScItemId(scItemId);
        QueryPlanDetailByAddressIdResponse salesPlanDetailResult = boSalesPlanDetailIndexService.queryPlanDetailByAddressId(addressIdRequest);

        if (Objects.isNull(salesPlanDetailResult) || CollectionUtils.isEmpty(salesPlanDetailResult.getResult())) {
            return Sets.newHashSet();
        }
        List<BoSalesPlanDetailIndex> salesPlanDetailList = salesPlanDetailResult.getResult();
        Set<String> planIdList = Sets.newHashSet();
        for (BoSalesPlanDetailIndex salesPlanDetail : salesPlanDetailList) {
//            String planId = salesPlanDetail.getPlanId();
//            // 筛选掉已完成的
//            LoadSalesPlanRequest loadSalesPlanRequest = new LoadSalesPlanRequest();
//            loadSalesPlanRequest.setId(planId);
//            SalesPlan salesPlan = null;
//            try {
//                salesPlan = salesPlanService.loadSalesPlan(loadSalesPlanRequest);
//            } catch (Exception e) {
//                log.error("月度计划查询异常", e);
//                continue;
//            }
//            if (Objects.isNull(salesPlan)) {
//                continue;
//            }
//            Integer status = salesPlan.getStatus();
//            if(SalesPlanStatusEnum.PUBLISHED.getCode().equals(status)) {
//                continue;
//            }
            SalesPlanDetail editSalesPlanDetailRecord = new SalesPlanDetail();
            BeanUtils.copyProperties(salesPlanDetail, editSalesPlanDetailRecord);
            editSalesPlanDetailRecord.setPlanId(Long.valueOf(salesPlanDetail.getPlanId()));
            editSalesPlanDetailRecord.setScItemLeafCategoryId(categoryId);
            editSalesPlanDetailRecord.setGmtModified(new Date());
            salesPlanDetailService.updateSalesPlanDetail(editSalesPlanDetailRecord);
            planIdList.add(String.valueOf(salesPlanDetail.getPlanId()));
            if (salesPlanDetail.getOspStatus() > SalesPlanStatusEnum.PUBLISHED.getCode()) {
                UpdateScItemCategoryRequest categoryRequest = new UpdateScItemCategoryRequest();
                categoryRequest.setScItemLeafCategoryId(categoryId);
                categoryRequest.setPlanDetailId(Objects.toString(salesPlanDetail.getId()));
                salesPlanAdjustDetailService.updateScItemCategory(categoryRequest);
            }
            com.epoch.app.bcorder.sales_plan.planscitemextend.dto.UpdateScItemCategoryRequest categoryRequest = new com.epoch.app.bcorder.sales_plan.planscitemextend.dto.UpdateScItemCategoryRequest();
            categoryRequest.setPlanId(String.valueOf(salesPlanDetail.getPlanId()));
            categoryRequest.setScItemId(salesPlanDetail.getScItemId());
            categoryRequest.setScItemCategoryId(categoryId);
            planScItemExtendService.updateScItemCategory(categoryRequest);
        }
        return planIdList;
    }

    @Override
    public Result<Boolean> sendMessageChangeCategory(SendMessageChangeCategoryInfo sendMessageChangeCategoryInfo) {
        try {
            String message = JSONObject.toJSONString(sendMessageChangeCategoryInfo);
            // 修改货品类目，触发相关汇总
            log.info("sendMessageChangeCategory_salesPlanCollectListener{}", message);
            Boolean aBoolean = messageService.sendMessage("sales_plan_item_change_message", "CR_SALES_PLAN_V2", "category_collect", message);
        } catch (Exception e) {
            log.error("货品类目变更消息发送异常", e);
        }
        return Result.success(true);
    }
}
